<template>
  <div>
    <!-- 面包屑 -->
    <admin-breadcrumb :breadcrumb="breadcrumb" />
    <!-- 标题输入 -->
    <el-input :ishljs="true" v-model="article.articleTitle" style="margin: 10px 0px;font-size: 18px;" placeholder="输入文章标题">
    </el-input>
    <el-row style="height: calc(100vh - 237px);">
      <!-- markdown编辑器 -->
      <mavon-editor codeStyle="darkula" :tabSize="4" v-model="article.articleContentMd" ref=md @save="publishArticle" style="height: 100%; min-height: 700px;" fontSize="16px">
        <!-- 插入一个按钮 -->
        <button slot="left-toolbar-after" type="button" class="op-icon el-icon-document" style="color:red" :title="'摘要/封面'" @click="abstractCoverDialogVisible = true"></button>
      </mavon-editor>
      <!-- 自定义的发布/取消按钮 -->
      <el-button class="editor-button" type="info" @click="triggerPublishArticle">发布</el-button>
      <el-button class="editor-button" type="info" @click="leave">取消</el-button>
    </el-row>
    <!-- 添加摘要封面对话框 -->
    <el-dialog :visible.sync="abstractCoverDialogVisible" width="50%">
      <el-divider content-position="left">摘要</el-divider>
      <el-input type="textarea" v-model="article.articleAbstract" rows="6" maxlength="255" show-word-limit></el-input>
      <el-divider content-position="left">封面</el-divider>
      <div style="margin-top: 20px">
        <el-input v-model="article.articleCover" autocomplete="off" placeholder="图片 URL" :disabled="true"></el-input>
        <img-upload @onUpload="uploadImg" ref="imgUploadRef" style="margin-top: 5px"></img-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="abstractCoverDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="abstractCoverDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImgUpload from "components/content/ImgUpload";
export default {
  name: "Editor",
  data() {
    return {
      // 文章对象
      article: {},
      // 发布文章对话框
      abstractCoverDialogVisible: false,

      // 修改文章专用变量，表示文章在后台的第几页
      pageNum: 0,

      // 0表示未被修改过
      articleState: 0,
    };
  },
  computed: {
    breadcrumb() {
      if (window.sessionStorage.getItem("article"))
        return ["内容管理", "文章列表", "修改文章"];
      else 
        return ["内容管理", "文章列表", "写文章"];
    },
  },
  components: {
    ImgUpload,
  },
  created() {
    // // 判断是不是修改文章。如果是修改文章，就要在编辑器中显示内容
    // if (this.$route.params.article) {
    //   this.article = this.$route.params.article;
    // } else if (window.sessionStorage.getItem("article"))
    if (window.sessionStorage.getItem("article") && window.sessionStorage.getItem("pageNum")) {
      this.article = JSON.parse(window.sessionStorage.getItem("article"));
      this.pageNum = JSON.parse(window.sessionStorage.getItem("pageNum"));
    }
  },
  methods: {
    // 发布文章，value 是 md，render 是 html
    async publishArticle(value, render) {
      console.log(this.article.articleAbstract)
      console.log(this.article.articleCover)
      console.log(this.article.articleTitle)

      if(this.article.articleAbstract===undefined || this.article.articleCover === undefined){
        const reslut = await this.$alert("请完成摘要/封面", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        }).catch((err) => err);
        if (reslut === "confirm") {
          return this.abstractCoverDialogVisible = true;
        }
      }
      if(this.article.articleTitle===undefined || this.article.articleTitle===''){
        const reslut = await this.$alert("请填写标题", "提示", {
          confirmButtonText: "确定",
          type: "warning",
        }).catch((err) => err);
        if (reslut === "confirm") {
          return;
        }
      }

      const reslut = await this.$confirm("是否发布文章?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      if (reslut !== "confirm") return this.$message.info("取消发布");

      // 判断是修改文章还是写文章
      // 发布被修改文章
      if (window.sessionStorage.getItem("article")) {
        const { data: res } = await this.$http.put(
          "/admin/article/" + this.pageNum,
          {
            id: this.article.id,
            articleTitle: this.article.articleTitle,
            articleAuthor: this.article.articleAuthor,
            articleContentMd: value,
            articleAbstract: this.article.articleAbstract,
            articleCover: this.article.articleCover,
            articleDate: null,
            pageNum: window.sessionStorage.getItem("pageNum"),
          }
        );
        if (res.code !== 200)
          return this.$message.error("服务器错误，修改失败");
        this.$message.success("修改成功");
        this.$router.replace("/admin/article");
      }
      // 发布新写的文章
      else {
        const { data: res } = await this.$http.post("/admin/article", {
          id: this.article.id,
          articleTitle: this.article.articleTitle,
          articleAuthor: JSON.parse(window.localStorage.getItem("user")).username,
          articleContentMd: value,
          articleAbstract: this.article.articleAbstract,
          articleCover: this.article.articleCover,
          articleDate: new Date().getTime(),
        });
        if (res.code !== 200)
          return this.$message.error("服务器错误，发布失败");
        this.$message.success("发布成功");
        this.$router.replace("/admin/article");
      }
    },

    // 上传图片
    uploadImg() {
      this.article.articleCover = this.$refs.imgUploadRef.url;
    },

    // 触发发布方法
    triggerPublishArticle() {
      this.publishArticle(this.article.articleContentMd, "");
    },
    // 取消发布并离开
    leave() {
      this.$router.replace("/admin/article");
    },
  },
};
</script>

<style lang="less" scoped>
.reminder {
  color: red;
  font-weight: 400;
}
.editor-button {
  float: left;
  margin-top: 8px;
  &:hover {
    color: red;
    background-color: white;
    text-decoration: underline;
  }
  &:last-child {
    margin-left: 20px;
  }
}
</style>
